package com.ie.service.admin;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ie.common.http.ResponseResult;
import com.ie.common.sercurity.utils.ConfigrarionBean;
import com.ie.common.sercurity.utils.JwtTokenUtil;
import com.ie.common.sercurity.utils.RedisUtil;
import com.ie.entity.AUserEntity;
import com.ie.mapper.admin.AUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: //TODO
 * @Author: xujia
 * @Date: 2024/9/3  22:29
 * @Param:
 * @version: 1.0
 * @Return:
 **/
@Service
@SuppressWarnings("all")
public class AUserServiceImpl extends ServiceImpl<AUserMapper, AUserEntity> implements AUserService{
    @Autowired
    private JwtTokenUtil jwtUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ConfigrarionBean config;

    /**
     * @Description: 管理员登录
     * @Author: xujia
     * @Date: 2024/9/3  22:29
     * @Param: [aUserEntity]
     * @version: 1.0
     * @Return: com.ie.common.http.ResponseResult<java.util.Map < java.lang.String, java.lang.String>>
     **/
    @Override
    public ResponseResult<Map<String, String>> login(AUserEntity aUserEntity) {
        //链式query
        //判断用户名是否存在
        long res = lambdaQuery().eq(AUserEntity::getAname, aUserEntity.getAname()).count();
        if(res == 0) {
            // 用户名不存在
            return ResponseResult.getMessageResult(null, "A001");
        }
        Map<String, String> mapparam = new HashMap<>();
        mapparam.put("aname", aUserEntity.getAname());
        mapparam.put("apwd", aUserEntity.getApwd());
        List<AUserEntity> mu = query().allEq(mapparam).list();
        //判断密码是否正确
        if (mu.size() > 0) {
            //生成token
            String token = jwtUtil.createToken(aUserEntity.getAname());
            /**使用了一个名为redisUtil的工具类来向Redis数据库中存储数据。具体来说，它将用户实体aUserEntity的名称（aname）作为键，
             并将该名称作为值，同时设置了一个过期时间
             */
            redisUtil.set("login_" + aUserEntity.getAname(), aUserEntity.getAname(), config.getRedisExpiration());
            Map<String, String> myres = new HashMap<>();
            myres.put("authtoken", token);
            myres.put("aname", aUserEntity.getAname());
            myres.put("aid", mu.get(0).getId()+"");
            return ResponseResult.getSuccessResult(myres);
        }else{//密码错误
            return ResponseResult.getMessageResult(null, "A002");
        }
    }
}

